﻿using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;

namespace ProjetoFase2
{
    public partial class SyncForm : Form
    {
        // delegate to access combobox
        delegate void BindComboBoxCallback();

        private int port;
        private string ip;
        private TcpClient clientSocket;
        private Thread syncThread;
        private NetworkStream stream;
        private DataSet receivedDataSet;
        private DataSet approved, unapproved;
        private UserLogin userLogin;
        private DataSet listaInativa;

        public SyncForm(string ip, int port, UserLogin userLogin, DataSet listaInativa)
        {
            InitializeComponent();

            this.Text += " - " + userLogin.Username;

            this.listaInativa = listaInativa;

            this.userLogin = userLogin;

            DatabaseConnector dbCon = new DatabaseConnector(userLogin.Username, userLogin.Password);

            this.ip = ip;
            this.port = port;

            approved = new DataSet();
            unapproved = new DataSet();

            dbCon.getResidenceDataSet("inactive", 1, approved);
            dbCon.getResidenceDataSet("inactive", 0, unapproved);
        }

        private void menuClose_Click(object sender, EventArgs e)
        {
            try
            {
                clientSocket.Close();
            }
            catch (Exception) { }

            this.Close();
        }

        private void BindComboBox()
        {
            panelSync.Visible = true;

            cmbConfirmed.DataSource = approved.Tables["residence"];
            cmbConfirmed.DisplayMember = "address";
            cmbConfirmed.ValueMember = "resi_id";

            cmbUnconfirmed.DataSource = unapproved.Tables["residence"];
            cmbUnconfirmed.DisplayMember = "address";
            cmbUnconfirmed.ValueMember = "resi_id";
        }

        private void btnSync_Click(object sender, EventArgs e)
        {
            btnSync.Enabled = false;
            panelSync.Visible = false;
            syncThread = new Thread(new ThreadStart(Sync));
            syncThread.Start();
        }

        private void Sync()
        {
            ServerInteraction servInt = new ServerInteraction(null, 0);
            DatabaseConnector dbCon = new DatabaseConnector(userLogin.Username, userLogin.Password);

            try
            {

                clientSocket = new TcpClient();
               
                clientSocket.Connect(ip, port);

                if (clientSocket.Client.Connected == true)
                {
                    // perform sync operations
                    stream = clientSocket.GetStream();

                    // write the supervisor id
                    servInt.writeString(stream, userLogin.Supervisor);

                    // read if it is ok
                    string ok = servInt.readString(stream);

                    if (ok == "valid")
                    {

                        servInt.writeDataSet(stream, listaInativa);

                        receivedDataSet = servInt.readDataSet(stream);

                        if (receivedDataSet != null)
                        {
                            // save data to database and load datasets to show the user what has been accepted
                            // and what was not accepted
                            dbCon.deleteAllResidences("inactive");

                            DataTableReader dtReader = receivedDataSet.CreateDataReader();

                            while (dtReader.Read())
                            {
                                Residence auxRes = new Residence(dtReader);
                                if (auxRes.Approved == 1)
                                    dbCon.insertResidence("inactive", auxRes);
                                else
                                    dbCon.insertResidence("active", auxRes);
                            }

                            approved.Clear();
                            unapproved.Clear();

                            dbCon.getResidenceDataSet("inactive", 1, approved);
                            dbCon.getResidenceDataSet("active", 0, unapproved);

                            if (this.panelSync.InvokeRequired)
                            {
                                BindComboBoxCallback bindBox = new BindComboBoxCallback(BindComboBox);
                                this.Invoke(bindBox);
                            }
                            else
                            {
                                BindComboBox();
                            }
                        }
                        else
                        {
                            MessageBox.Show("There was an error on the supervisor!");
                        }

                    }
                    else
                    {
                        MessageBox.Show("The PDA you were trying to connect is not your\nsupervisor's!");
                    }

                }
            }
            catch (Exception) { }
        }

    }
}